package com.homedo.odin.solution.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.base.service.BaseService;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.odin.solution.dao.UserActionLogMapper;
import com.homedo.odin.solution.enumcode.statistics.UserActionBusinessTypeEnum;
import com.homedo.odin.solution.model.entity.UserActionLog;
import com.homedo.odin.solution.model.request.mng.useractionlog.UserActionLogListRequestBean;
import com.homedo.odin.solution.model.response.mng.useractionlog.UserActionLogPageResponseBean;
import com.homedo.odin.solution.model.response.mng.useractionlog.UserActionLogResponseBean;
import java.util.Collections;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * <p> 解决方案分类记录  服务实现类 </p>
 *
 * @author ZhangLei
 * @date 2018-05-15
 * @Description:
 */
@Service
public class UserActionLogServiceImpl extends BaseService<UserActionLogMapper, UserActionLog> {

    public UserActionLogPageResponseBean getLogs(UserActionLogListRequestBean requestBean, String businessType) {
        PageHelper.startPage(requestBean.getPageNum(), requestBean.getPageSize());

        List<UserActionLogResponseBean> logs;
        if (requestBean.isWithUser()) {
            logs = baseMapper.getLogsWithUserInfo(requestBean.getBusinessId(), businessType);
        } else {
            logs = baseMapper.getLogs(requestBean.getBusinessId(), businessType);
        }
        PageInfo<UserActionLogResponseBean> pageInfo = new PageInfo<>(logs);
        List<UserActionLogResponseBean> dbList = pageInfo.getList();

        if (CollectionUtils.isEmpty(dbList)) {
            return null;
        }
        return BeanUtils.transfrom(UserActionLogPageResponseBean.class, pageInfo);
    }

    /**
     * 记录日志
     */
    @Async()
    public void recordLog(UserActionLog log) {
        if (!UserActionBusinessTypeEnum.dbValueExist(log.getBusinessType())) {
            throw new BizException(Meta.CODE_451.getCode(), "无效的业务类型");
        }
        logger.info("开始保存用户行为日志信息...");
        baseMapper.insert(log);
    }

    /**
     * 获取该业务分类下已有的位置列表
     */
    public List<String> getPositions(String bizType) {
        if (StringUtils.isEmpty(bizType)) {
            return Collections.emptyList();
        }
        return baseMapper.getPositions(bizType);
    }
}
